<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>第二章JavaScript语法</title>
    <link href="index.css" rel="stylesheet"/>
</head>
<body>
<h1>图片美术馆</h1>
<ul id="ul_photo">
    <li>
        <a href="图片1.jpg" title="图片1">图片1</a>
    </li>
    <li>
        <a href="图片2.jpg" title="图片2">图片2</a>
    </li>
    <li>
        <a href="图片3.jpg" title="图片3">图片3</a>
    </li>
</ul>
<br/>

<script type="text/javascript">
    /**
     * 代码创建img和p
     * insertBefore 在什么之前插入
     * nextSibling 下一个兄弟元素
     * lastChild 最有一个子元素
     * 新增insertAfter方法
     */
    function insertAfter(newElement, targetElement) {
        var parentNode = targetElement.parentNode;
        if (parentNode.lastChild === targetElement) {
            parentNode.appendChild(newElement);
        } else {
            var targetNextElement = targetElement.nextSibling;
            parentNode.insertBefore(newElement, targetNextElement);
        }
    }

    function createPlaceHolder() {
        var ulPhoto = document.getElementById("ul_photo");
        var imgPhoto = document.createElement("img");
        var pPhoto = document.createElement("p");
        imgPhoto.setAttribute("id", "img_place");
        imgPhoto.setAttribute("src", "图片默认.jpg");
        pPhoto.setAttribute("id", "p_place");
        pPhoto.appendChild(document.createTextNode("默认图片"))
        insertAfter(imgPhoto, ulPhoto);
        insertAfter(pPhoto, imgPhoto);

        //加一个BR
        ulPhoto.parentNode.insertBefore(document.createElement("br"), imgPhoto);
    }

    function linkClick() {
        if (!document.getElementById) return false;
        if (!document.getElementsByTagName) return false;
        var ulPhoto = document.getElementById("ul_photo");
        var aArray = ulPhoto.getElementsByTagName("a");
        for (var i = 0; i < aArray.length; i++) {
            aArray[i].onclick = function () {
                showPic(this);
                return false;
            }
        }
    }

    function showPic(whichPic) {
        if (!document.getElementById) return false;
        if (!document.getElementsByTagName) return false;
        var imgPlace = document.getElementById("img_place");
        var pPlace = document.getElementById("p_place");
        var picSrcPath = whichPic.getAttribute("href");
        var title = whichPic.getAttribute("title");
        imgPlace.setAttribute("src", picSrcPath);
        pPlace.firstChild.nodeValue = title;
    }

    function addLoad(newFunction) {
        var preFunction = window.onload;
        if (typeof preFunction !== "function") {
            window.onload =newFunction();
        }else{
            window.onload = function () {
                preFunction();
                newFunction();
            };
        }
    }

    addLoad(createPlaceHolder);
    addLoad(linkClick);
</script>
</body>
</html>